package org.endy.leisure.diaTracker.service

import org.endy.leisure.diaTracker.entity.announcement.Announcement
import org.endy.leisure.diaTracker.entity.announcement.AnnouncementView
import org.endy.leisure.diaTracker.entity.announcement.ReadAnnouncement
import org.endy.leisure.diaTracker.repository.AnnouncementRepository
import org.endy.leisure.diaTracker.repository.AnnouncementViewRepository
import org.springframework.stereotype.Service

/**
 * 公告服务：发布公告、查询公告，阅读公告
 */
@Service
class AnnouncementService(
    private val announcementRepository: AnnouncementRepository,
    private val announcementViewRepository: AnnouncementViewRepository
) {

    /**
     * 发布公告
     */
    fun publisher(announcement: Announcement) {
        announcementRepository.save(announcement)
    }

    /**
     * 删除公告
     */
    fun dropAnnouncement(announcementId: Long) {
        announcementRepository.deleteById(announcementId)
    }

    /**
     * 查询所有公告，并关联公告状态
     */
    fun queryAnnouncementStatus(userId: Long): List<ReadAnnouncement>? {
        // 查找所有公告
        val allAnnouncement = announcementRepository.findAll()
        var allReadAnnouncement: List<ReadAnnouncement>? = null
        if (allAnnouncement.isNotEmpty()) {
            // 所有都为未读
            allReadAnnouncement = allAnnouncement.map { a ->
                ReadAnnouncement(
                    a.id!!,
                    a.title,
                    a.content,
                    a.type,
                    a.publisher,
                    a.createTime,
                    readStatus = 0
                )
            }.toList()
        }
        // 查找所有用户已经阅读过的状态
        val allUserView = announcementViewRepository.findAnnouncementViewByUserId(userId)
        if (allReadAnnouncement != null && allUserView != null && allUserView.isNotEmpty()) {
            // 比对状态
            allReadAnnouncement.map { r ->
                if (allUserView.any { r.id == it.announcementId }) {
                    r.readStatus = 1
                }
                r
            }

        }
        return allReadAnnouncement
    }

    /**
     * 查询所有公告
     */
    fun queryAll(): List<Announcement> {
        return announcementRepository.findAll()
    }

    /**
     * 用户阅读公告
     */
    fun readAnnouncement(userId: Long, announcementId: Long): Announcement? {
        // 用户已经阅读过公告就不需要再次阅读公告
        announcementViewRepository.findUserAnnouncementByUserIdAndAnnouncementId(userId, announcementId)
            ?: announcementRepository.findById(announcementId).ifPresent { announcement ->
                announcementViewRepository.save(
                    AnnouncementView(
                        userId = userId,
                        announcementId = announcementId,
                        readStatus = 1
                    )
                )
            }

        return announcementRepository.findById(announcementId).get()
    }

}